/*
 * Copyright (C) 2011 Dirk Weißenborn, dirk.weissenborn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weissenborn.colabtex.server.helpers;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

/**
 * The Class MailHelper is a simple mail helper class
 */
public class MailHelper {	
	
	/** The email. */
	private MultiPartEmail email;
	
	/**
	 * Instantiates a new mail helper.
	 *
	 * @param ini the ini file
	 * @param what the what
	 * @throws EmailException the email exception
	 */
	public MailHelper(String ini, String what) throws EmailException {		
		Properties props = new Properties();
		try {
			props.load(getClass().getClassLoader().getResourceAsStream(ini));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		email = new MultiPartEmail();
		
		
		
		email.setHostName(props.getProperty("email.host", "localhost"));
		email.setSmtpPort(Integer.parseInt(props.getProperty("smtp.port", "25")));
		email.setAuthenticator(new DefaultAuthenticator(props.getProperty("email.sender.name"), props.getProperty("email.sender.password")));
		
		email.setFrom(props.getProperty("email.sender.name"));
		email.setSubject(props.getProperty("email.sender.subject"));
		email.setMsg(what);		
		//email.setTLS(true);
	}
	
	/**
	 * Send mail.
	 *
	 * @param to the to
	 * @return the boolean
	 */
	public Boolean sendMail(String to) {
		try {
			email.addTo(to);
			email.send();
		} catch (EmailException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	
	/**
	 * Adds the attachment.
	 *
	 * @param path the path
	 * @return the boolean
	 */
	public Boolean addAttachment(String path) {
		EmailAttachment attachment = new EmailAttachment();
		attachment.setPath(path);
		attachment.setDisposition(EmailAttachment.ATTACHMENT);	
		
		try {
			email.attach(attachment);
		} catch (EmailException e) {
			return false;
		}
		
		return true;
	}

}
